package org.luxor.commons.websocket.component.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * WebSocket会话本地存储器
 *
 * @author Mr.yan  @date 2021/9/4
 */
public class WsSimpleSessionStorage implements WsSessionStorage {
    private static final Logger logger = LoggerFactory.getLogger(WsSessionStorage.class);

    /**
     * 会话内存存储器
     */
    private final ConcurrentMap<String, Session> memoryStore = new ConcurrentHashMap();

    /**
     * 添加会话
     *
     * @param token
     * @param session
     */
    @Override
    public void addSession(String token, Session session) {
        if (existSession(token)) {
            logger.info("cover the existing token-session. token:" + token);
        }
        memoryStore.put(token, session);
    }

    /**
     * 移除会话
     *
     * @param token
     */
    @Override
    public void removeSession(String token) {
        memoryStore.remove(token);
    }

    /**
     * 普通消息
     *
     * @param token
     * @param message
     * @return
     */
    @Override
    public void send(String token, String message) {
        if (existSession(token)) {
            RemoteEndpoint.Basic remoteEndpoint = memoryStore.get(token).getBasicRemote();
            try {
                remoteEndpoint.sendText(message);
            } catch (IOException e) {
                logger.warn("fail to send, token:" + token, e);
            }
        } else {
            logger.warn("failed to send message, the token-session does not exist.");
        }
    }

    /**
     * 群发消息
     *
     * @return
     */
    @Override
    public void sendAll(String message) {
        for (Map.Entry<String, Session> entry : memoryStore.entrySet()) {
            try {
                RemoteEndpoint.Basic remoteEndpoint = entry.getValue().getBasicRemote();
                remoteEndpoint.sendText(message);
            } catch (IOException e) {
                logger.warn("fail to send, token:" + entry.getKey(), e);
            }
        }
    }

    /**
     * 存在会话？
     *
     * @param token
     * @return
     */
    @Override
    public boolean existSession(String token) {
        return memoryStore.keySet().contains(token);
    }
}
